﻿#region Librerias

using System.IO;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using co.com.certicamara.toSignObject.certificates;
using co.com.certicamara.toSignObject.core;
using co.com.certicamara.toVerifyObject.core;
using ESF.General;
using ESF.SFT.FileUploader.Config;

#endregion


namespace ESF.SFT.FileUploader.Helpers
{
	public static class CerticamaraHelper
	{
		/// <summary>
        /// Lógica de recuperación del certificado digital del firmante
        /// </summary>
        /// <returns></returns>
        public static X509Certificate2 GetSignerCertificate (string pCERFileName, string pCERPassword, bool pUseToken)
        {   
			X509Certificate2 signerCertificate;

			SecureString p12CurrentPassword;


            if (pUseToken == true)
            {
                signerCertificate = new CertificateManagement("My").selectCertificate();
            }
            else
            {
				p12CurrentPassword = new SecureString ();

                for (int i = 0; i < pCERPassword.Length; i++)
                {
                    p12CurrentPassword.AppendChar (pCERPassword [i]);
                }

                signerCertificate = CertificateManagement.loadPKCS12SignerCertificate(pCERFileName, p12CurrentPassword);
            }
			
			return signerCertificate;
        }


		public static void VerifySignedFile (FileInfo pFileSigned)
		{
			new CMSAttachedVerifier (File.ReadAllBytes (pFileSigned.FullName)).verify (false);
		}


		public static FileInfo SignFile (FileInfo pFileToSign, string pCERFileName, string pCERPassword, bool pUseToken)
        {
			X509Certificate2 signerCertificate;

			CmsAttachedToSignObject signer;

			FileInfo fileSigned;

			byte[] signedFileContents;
			

			signerCertificate = GetSignerCertificate (pCERFileName, pCERPassword, pUseToken);
                
			signer = new CmsAttachedToSignObject (File.ReadAllBytes (pFileToSign.FullName), signerCertificate);
                
            signedFileContents = signer.signMessage (pFileToSign.FullName);

			fileSigned = new FileInfo (pFileToSign.FullName + ".p7z");

			FileHelper.Delete (fileSigned.FullName);

			File.WriteAllBytes (fileSigned.FullName, signedFileContents);

            VerifySignedFile (fileSigned);


			return fileSigned;
        }
	}
}
